import json
import os
from typing import Dict, Any


class ConfigLoader:
    """配置文件加载器"""

    def __init__(self, config_path: str = "config.json"):
        self.config_path = config_path
        self._config = None
        self._load_config()

    def _load_config(self):
        """加载配置文件"""
        try:
            if not os.path.exists(self.config_path):
                raise FileNotFoundError(f"配置文件不存在: {self.config_path}")

            with open(self.config_path, 'r', encoding='utf-8') as f:
                self._config = json.load(f)

            # 验证配置格式
            self._validate_config()

        except Exception as e:
            raise Exception(f"加载配置文件失败: {str(e)}")

    def _validate_config(self):
        """验证配置文件格式"""
        required_keys = ['resources', 'processes', 'system']
        for key in required_keys:
            if key not in self._config:
                raise ValueError(f"配置文件缺少必需的键: {key}")

        # 验证资源配置
        resources = self._config['resources']
        for name, config in resources.items():
            if 'type' not in config or 'vector_index' not in config:
                raise ValueError(f"资源 {name} 配置不完整")
            if config['type'] not in ['exclusive', 'shared']:
                raise ValueError(f"资源 {name} 类型必须是 'exclusive' 或 'shared'")

        # 验证进程配置
        processes = self._config['processes']
        for name, config in processes.items():
            required_process_keys = ['command', 'resources', 'enabled']
            for key in required_process_keys:
                if key not in config:
                    raise ValueError(f"进程 {name} 缺少必需的配置: {key}")

            # 验证资源向量长度
            if len(config['resources']) != 4:
                raise ValueError(f"进程 {name} 的资源向量必须是4位")

    @property
    def config(self) -> Dict[str, Any]:
        """获取完整配置"""
        return self._config

    @property
    def resources(self) -> Dict[str, Any]:
        """获取资源配置"""
        return self._config['resources']

    @property
    def processes(self) -> Dict[str, Any]:
        """获取进程配置"""
        return self._config['processes']

    @property
    def system(self) -> Dict[str, Any]:
        """获取系统配置"""
        return self._config['system']

    def get_resource_names(self) -> list:
        """获取按向量索引排序的资源名称列表"""
        resources = []
        resource_map = {}

        for name, config in self.resources.items():
            resource_map[config['vector_index']] = name

        # 按索引顺序排列
        for i in range(4):
            if i in resource_map:
                resources.append(resource_map[i])
            else:
                raise ValueError(f"资源向量索引 {i} 未定义")

        return resources

    def get_exclusive_resource_indices(self) -> list:
        """获取独占资源的向量索引列表"""
        exclusive_indices = []
        for name, config in self.resources.items():
            if config['type'] == 'exclusive':
                exclusive_indices.append(config['vector_index'])
        return sorted(exclusive_indices)

    def get_enabled_processes(self) -> Dict[str, Any]:
        """获取启用的进程配置"""
        enabled_processes = {}
        for name, config in self.processes.items():
            if config.get('enabled', True):
                enabled_processes[name] = config
        return enabled_processes


# 全局配置实例
config_loader = ConfigLoader()